﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace gt.framework.Security
{
    public class RSAPrivateKey
    {
        public byte[] Modulus;
        public byte[] D;

        public static RSAPrivateKey FromXmlString(string xmlString)
        {
            if (string.IsNullOrEmpty(xmlString)) return null;

            try
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
                {
                    if (!reader.ReadToFollowing("RSAKeyValue")) return null;
                    if (reader.LocalName != "Modulus" && !reader.ReadToFollowing("Modulus")) return null;
                    string modulus = reader.ReadElementContentAsString();

                    if (reader.LocalName != "D" && !reader.ReadToFollowing("D")) return null;
                    string d = reader.ReadElementContentAsString();

                    RSAPrivateKey privateKey = new RSAPrivateKey();
                    privateKey.Modulus = Convert.FromBase64String(modulus);
                    privateKey.D = Convert.FromBase64String(d);

                    return privateKey;
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
